package controller;

import boundary.IMenu;
import entity.IData;

public class MenuController implements Runnable, IMenuController {

	private IMenu menu;
	private IData data;
	private boolean dState;

	public MenuController(IMenu menu, IData data) {
		this.menu = menu;
		this.data = data;
		dState = false;
	}

	/* (non-Javadoc)
	 * @see controller.IMenuController#run()
	 */
	@Override
	public void run() {
		data.setTaraWeight(0);
		data.setWeight(0);
		String answer;
		do{
			answer=askMenu().toUpperCase();
			
			switch(answer){
			case "T":
				data.setTaraWeight(data.getWeight());
				break;
			case "B":
				data.setWeight(menu.askDouble());
				break;
			case "Q":
				menu.print("Du har valgt at afslutte");
				break;
			default:
				menu.print("Dine muligheder er: 'B' = brutto - 'T' = tara - 'Q' = quit");
				break;
			}
		}
		while (!answer.equals("Q"));
	}

	@Override
	public String showRM20() {
		String output;
		if (menu.getLock().tryLock()){
			output = menu.showRM20(data.getTaraWeight(), data.getWeight(), data.getRM201(), data.getRM202(), data.getRM203(), data.getDebug1(), data.getDebug2());
			menu.getLock().unlock();
		} else {
			output = "Vægten er optaget.";
		}
		data.setRM20("", "", "");
		return output;
	}

	@Override
	public void resetRM20() {
		menu.showMenu(data.getTaraWeight(), data.getWeight(), data.getP111(), data.getRM201(), data.getRM202(), data.getRM203(), dDisplay(), data.getDebug1(), data.getDebug2());
	}
	
	@Override
	public void upDisplay(boolean dState){
		if (dState){
			this.dState = true;
		} 
		if (!menu.getLock().isLocked()){
			menu.showMenu(data.getTaraWeight(), data.getWeight(), data.getP111(), data.getRM201(), data.getRM202(), data.getRM203(), dDisplay(), data.getDebug1(), data.getDebug2());			
		}
	}

	@Override
	public void resetDisplay() {
		dState = false;
		menu.showMenu(data.getTaraWeight(), data.getWeight(), data.getP111(), data.getRM201(), data.getRM202(), data.getRM203(), dDisplay(), data.getDebug1(), data.getDebug2());
	}
	
	@Override
	public String dDisplay(){
		String out;
		if (dState){
			out = data.getDisplay();
		} else {
			out = String.format("%.4f", data.getWeight()-data.getTaraWeight());
		}
		return out;
	}
	
	public String askMenu() {
		String output ="";
		menu.setRM20(null);
		int i = 0;
		while (i < 1){
			menu.showMenu(data.getTaraWeight(), data.getWeight(), data.getP111(), data.getRM201(), data.getRM202(), data.getRM203(), dDisplay(), data.getDebug1(), data.getDebug2());
			output = menu.scan();
			if (menu.getLock().isLocked()){
				i = -1;
				menu.setRM20(output);
			}
			i++;
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return output;
	}

	@Override
	public void connected(String inetAddress) {
		menu.connected(inetAddress);		
	}

	@Override
	public void unConnected(String inetAddress) {
		menu.unConnected(inetAddress);
	}
}
